package com.cloud.base.threadPool;

import java.util.concurrent.*;

public class ThreadPoolMain {
    public static void main(String[] args) {
        // 线程可复用，但是无法指定线程池大小
        ExecutorService executor1 = Executors.newCachedThreadPool();
        executor1.execute(() -> {
            System.out.println("newCachedThreadPool");
        });
        // 可指定线程池大小
        ExecutorService executor2 = Executors.newFixedThreadPool(1);
        executor2.execute(() -> {
            System.out.println("newFixedThreadPool");
        });

        // 定时执行  3  第一次延迟3秒执行，之后每隔1秒执行一次
        //scheduleAtFixedRate  如果间隔时间小于任务的执行时间，那么任务执行结束之后，会立马执行，至此间隔时间就会被打乱。
        ScheduledExecutorService executor3 = Executors.newScheduledThreadPool(5);
        executor3.scheduleAtFixedRate(() -> {
            System.out.println("newScheduledThreadPool");
        }, 3, 1, TimeUnit.SECONDS);

        // 定时执行  3  第一次延迟3秒执行，之后每隔1秒执行一次
        //scheduleWithFixedDelay  间隔时间不会受任务执行时间长短的影响。
        ScheduledExecutorService executor4 = Executors.newScheduledThreadPool(5);
        executor4.scheduleWithFixedDelay(() -> {
            System.out.println("newScheduledThreadPool");
        }, 3, 1, TimeUnit.SECONDS);

        // 只有一个线程
        ExecutorService executor5 = Executors.newSingleThreadExecutor();
        executor5.execute(() -> {
            System.out.println("newScheduledThreadPool");
        });

        ThreadPoolExecutor threadPoolExecutor =
                new ThreadPoolExecutor(5, 10,
                        1, TimeUnit.SECONDS,
                        new ArrayBlockingQueue<Runnable>(10),
                        Executors.defaultThreadFactory(), (r, executor) -> {
                    //打印丢弃的任务
                    System.out.println(r.toString() + " is discard");
                });
        threadPoolExecutor.execute(() -> {
            System.out.println("自定义线程池");
        });
    }
}
